package com.yokead.common.scheduling;


import com.yokead.service.nginxlog.NginxLog2019Service;
import com.yokead.service.nginxlog.NginxLogAnalysisService;
import com.yokead.system.log.SystemLog;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * nginx日志分析
 *
 * @author yangheng
 */
@Component
public class NginxLogTask {

    @Resource
    private NginxLogAnalysisService nginxLogAnalysisService;
    @Resource
    private NginxLog2019Service nginxLog2019Service;

    /**
     * 每次开启分析日志设为false. 分析完成后再改回来。
     * 在此期间。不允许其他线程在进入执行
     */
    private AtomicBoolean atomicBoolean = new AtomicBoolean(true);

    /**
     * 每2个小时执行一次
     */
    @Scheduled(cron = "0 0 */2 * * ?")
    public void nginxLog2019() {
        SystemLog.LOG().error("开始进行nginx日志分析");
        if (!atomicBoolean.get()) {
            SystemLog.LOG().error("上次分析还未结束。放弃");
            return;
        }
        try {
            atomicBoolean.set(false);
            nginxLogAnalysisService.startAnalysis();
        } catch (Exception e) {
            SystemLog.ERROR().error("nginx日志分析过程中出现异常", e);
        }
        atomicBoolean.set(true);
    }


    /**
     * 每个月10号删除三个月前的数据
     */
    @Scheduled(cron = "0 0 0 10 * ? ")
    public void delete() {
        nginxLog2019Service.deleteOldData();
    }
}
